package controller.v2;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.alibaba.fastjson.JSONObject;


import model.MemberVO;
import model.WeixinOauth2TokenVO;
import service.v2.ConfigService;
import service.v2.MemberChildService;
import service.v2.MemberService;
import service.v2.WeChatService;
import service.v2.WechatLoginService;
import util.ConfigUtil;
import util.PackageUtil;
import util.SecurtiyKit;
import util.Sha1;
import util.WeixinUtil;
import util.XMLUtil;

@Controller	
@RequestMapping("/v2/wechat")
public class WechatController {
	
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private WechatLoginService wechatLoginService;
	
	@Autowired
	private ConfigService configService;
	
	@Autowired
	private WeChatService wechatservice;
	
//	//"media_id"设定 运维和测试不同id
//    public static  String ID1 = null;
//    public static  String ID2 = null;
//    public static  String ID3 = null;
//    public static  String ID4 = null;
//    static{
//   	 Properties env;
//		try {
//			env = PropertiesLoaderUtils.loadAllProperties("env_mng.properties");
//			String envCode = env.getProperty("env");
//			if(envCode.equals("dev")){
//				//240测试公众平台
//				//ID1 = "zB236e1vtmBRdcmVWzSQLJXXVEMz5lQ8Jlt3aweD8WA";//注册就推送图片
//				ID2 = "zB236e1vtmBRdcmVWzSQLJXXVEMz5lQ8Jlt3aweD8WA";//关键字回复 黑马计划推送图片
//				ID3 = "zB236e1vtmBRdcmVWzSQLJXXVEMz5lQ8Jlt3aweD8WA";//关键字友米乐回复 推送图片
//				ID4 = "zB236e1vtmBRdcmVWzSQLJXXVEMz5lQ8Jlt3aweD8WA";//普通接收消息自动回复推送图片
//			}else{
//				///运维公众平台
//				//ID1 = "r_7Pf0Ro0Svq4aPuEsVWofikv8pDWM84h37P5bDOi40";//注册就推送图片
//				ID2 = "r_7Pf0Ro0Svq4aPuEsVWoZfl8R1L58voz3kUxZVZmV0";//关键字回复 黑马计划推送图片
//				ID3 = "r_7Pf0Ro0Svq4aPuEsVWobSK5Yv7Jj_KkpIpiqbGkn0";//关键字友米乐回复 推送图片
//				ID4 ="r_7Pf0Ro0Svq4aPuEsVWoZfl8R1L58voz3kUxZVZmV0";//普通接收消息自动回复推送图片
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	 }
/*    @RequestMapping(value="/innit",method=RequestMethod.GET)
    public void WeChatOtherEvent(HttpServletRequest request, HttpServletResponse response) throws Exception{
    	//接入代码 接入时把POST方法改成GET
        String signature = request.getParameter("signature");
    	String timestamp = request.getParameter("timestamp");
    	String nonce = request.getParameter("nonce");
    	String echostr = request.getParameter("echostr");
    	
    	String[] arrs = {ConfigUtil.WECHAT_TOKEN,nonce,timestamp};
    	Arrays.sort(arrs);
    	StringBuffer sb = new StringBuffer();
    	for(String a : arrs){
    		sb.append(a);
    	}
    	String sha1 = SecurtiyKit.sha1(sb.toString());
    	System.out.println(sha1.equals(signature));
    	if(sha1.equals(signature)){
    		response.getWriter().println(echostr);
    	}
    }*/
	@RequestMapping(value="/innit",method=RequestMethod.POST)
	public void WeChatOtherEvent(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		String content=null;
		String media_id=null;
    	//content="<a href='http://wechat-java-mall.uniposts.com/index/goodDetail.do?good_id=865&from=timeline'>>>查看详情:</a>";

        //获取ACCESS_TOKEN
		String access_token = wechatservice.getAccessToken();
        //推送返回结果
        String re = null;
        //用户昵称
        String s_nickname = null;
        String x_nickname = null;
        
		//项目名称获取 "友米乐"
		String app_name = configService.loadConfig("APP_NAME");
		
		String strxml = XMLUtil.requestToString(request);
        Map<String, String> map =  XMLUtil.doXMLParse(strxml);
        
        // 返回时间  
        Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;
        
        System.out.println(map.get("ToUserName"));
        System.out.println(map.get("FromUserName"));
        System.out.println(map.get("CreateTime"));
        System.out.println(map.get("MsgType"));
        System.out.println(map.get("Event"));
        System.out.println(map.get("EventKey"));
        System.out.println(map.get("Ticket"));
        
        //公众号点击关注时推送事件
        if("subscribe".equals(map.get("Event"))){
        	String union_id= WeixinUtil.getUnionId(map.get("FromUserName"),access_token);
        	
        	if(!"errcode".equals(union_id)){
        		MemberVO membervo = memberService.selectMemberInfoByUnionId(union_id);
        		
        		if(membervo!=null){
        			memberService.updataPushOpenId(membervo.getId(),map.get("FromUserName"));
        		}
        			memberService.deleteMemberOpenByUnionId(union_id);
        			memberService.insertOpenIdAndPushOpenId(map.get("FromUserName"),union_id);
        	}
        	
        	//只要有关注事件 就推送这句话。
            StringBuffer str = new StringBuffer();  
            str.append("欢迎加入全球好货买卖委员会！").append("\n\n");
            str.append("我是友米，专为宝宝们提供：").append("\n\n");
            str.append("🎉全球正品好货，").append("\n\n");
            str.append("🎉推送最新优惠，").append("\n\n");
            str.append("🎉提供共享会员制服务，").append("\n\n");
            str.append("🎉还能助您轻创业！").append("\n\n");
            str.append("欢迎前来勾搭，或者自由探索底部菜单，在输入框输入您的咨询问题~");
            content=str.toString();
        	wechatservice.sendWeChatMsgCommonMethod1(map.get("FromUserName"),content);
        	content=null;
        	
        }
        //CLICK 事件推送事件
        if("CLICK".equals(map.get("Event"))){
        	//点击菜单拉取消息时的事件推送
        	//友米客服
        	if("V1001_Service".equals(map.get("EventKey"))){
        		StringBuffer buffer = new StringBuffer();
        		buffer.append("我是友米，有什么能帮你的，尽管开口啊，虽然我很忙！[偷笑] 或者去【友米乐商城】找我们的客服小姐姐聊聊呗~");
            	content=buffer.toString();
            	wechatservice.sendWeChatMsgCommonMethod1(map.get("FromUserName"),content);

            	content=null;
        	}
        	//点击菜单拉取消息时的事件推送
        	//联系友米
        	if("V1002_Join".equals(map.get("EventKey"))){
        		StringBuffer buffer = new StringBuffer();
        		buffer.append("亲爱的会员！加盟友米乐，请在公众号直接留言，留下您的联系方式：微信号或手机号，小友会火速联系您，欢迎加入这个大家庭！");
            	content=buffer.toString();
            	wechatservice.sendWeChatMsgCommonMethod1(map.get("FromUserName"),content);
            	content=null;
        	}
        }
        if("text".equals(map.get("MsgType"))){
        	//黑马计划
        	if("黑马".equals(map.get("Content")) 
        	 ||"黑马计划".equals(map.get("Content"))
        	 ||"黑马行动".equals(map.get("Content"))
        	 ||"友米乐黑马".equals(map.get("Content"))
        	 ||"黑马计划是什么".equals(map.get("Content"))){
        		StringBuffer buffer = new StringBuffer();
        		
        		buffer.append("友米乐创业黑马行动计划送你7500元创业基金，你敢创业吗！").append("\n\n");
        		buffer.append("资源一：7500元项目启动金").append("\n\n");
        		buffer.append("资源二：首批招募1000名创业大将").append("\n\n");
        		buffer.append("资源三：友米乐新社交电商平台及市场资源共享").append("\n\n");
        		buffer.append("资源四：海陆空全能创业涅槃培训").append("\n\n");
        		buffer.append("资源五：1对1灵魂创业导师带队").append("\n\n");
        		buffer.append("创业大赛报名步骤：").append("\n\n");
        		buffer.append("01创业精英可关注【友米乐】微信公众平台，点击右下角【创业黑马】，按照要求详细填写报名表，点击【提交】即可完成报名；").append("\n\n");
        		buffer.append("02创业精英可下载【友米乐】，注册登录后点击首页Banner或【友米头条】内的【友米乐创业黑马行动计划】，按照要求详细填写报名表，点击【提交】即可完成报名；");
        		content=buffer.toString();
        		wechatservice.sendWeChatMsgCommonMethod1(map.get("FromUserName"),content);
            	content=null;
            	//
            	wechatservice.sendWeChatImgCommonMethod1(map.get("FromUserName"),WeixinUtil.ID2);

        		
        	}else if("友米乐".equals(map.get("Content")) //友米乐
        			||"友米乐是什么".equals(map.get("Content"))
        			||"友米乐是做什么的".equals(map.get("Content"))
        			||"友米乐黑马计划".equals(map.get("Content"))){
        		
                StringBuffer buffer = new StringBuffer();
        		buffer.append("1.    商机无限，尽在掌中，友米乐欢迎你的到来。").append("\n");
        		buffer.append("2.    友米乐 秉承“链接，分享，乐在其中”的互联网理念，引领新一代全球社交电商消费行业发展。").append("\n");
        		buffer.append("3.    友米乐开启社交分享的商业革命，秉承“链接，分享，乐在其中”的互联网理念，为消费者提供品质生活的悦享平台，助力全球会员快乐消费，为销售群体、创业者提供搭载链接分享、加速系统壁垒的轻创业新型社交电商平台。");
        		
        		content=buffer.toString();
        		wechatservice.sendWeChatMsgCommonMethod1(map.get("FromUserName"),content);
            	content=null;
            	//
            	wechatservice.sendWeChatImgCommonMethod1(map.get("FromUserName"),WeixinUtil.ID3);
        		
        	}else if("A".equals(map.get("Content")) 
        			||"a".equals(map.get("Content"))){
        		
                StringBuffer buffer = new StringBuffer();
        		buffer.append("A、财运状况极佳").append("\n");
        		buffer.append("[愉快]2018年你的财运状况极佳，你的正财运和偏财运都非常的好。正财运会帮助你财源广进，快速的积累财富。偏财运会帮你快速的增加多余的财富，以应对不时之需。所以在2018年，你不用为财富所烦恼，只要不出岔子，你的财富会一直累积。").append("\n");
        		
        		content=buffer.toString();
        		wechatservice.sendWeChatMsgCommonMethod1(map.get("FromUserName"),content);
            	content=null;
        		
        	}else if("B".equals(map.get("Content")) 
        			||"b".equals(map.get("Content"))){
        		
                StringBuffer buffer = new StringBuffer();
        		buffer.append("B、财运状况良好").append("\n");
        		buffer.append("[憨笑]2018年你的财运状况良好。在这一年里，你的财运呈现上升的趋势。相比于往年，今年投资的项目都会得到一些反馈。这些反馈会帮助你积累财富。虽然也会遇到一些不小的问题，但是总能很快的解决。所以在这一年，要好好擦亮眼睛，找准投资的项目").append("\n");
        		
        		content=buffer.toString();
        		wechatservice.sendWeChatMsgCommonMethod1(map.get("FromUserName"),content);
            	content=null;
        		
        	}else if("C".equals(map.get("Content")) 
        			||"c".equals(map.get("Content"))){
        		
                StringBuffer buffer = new StringBuffer();
        		buffer.append("C、财运状况一般").append("\n");
        		buffer.append("[微笑]2018年里你的财运状况一般。和往年一样，财运状况基本无差。处于一种十分平淡的状态，如果不需要很大的开销，这种状态还能维持很长的时间，但是如果突然增大了开销，那么这个财运的状况将会给你带来很大的烦恼。你会发现入不敷出，开始变得拮据起来。").append("\n");
        		
        		content=buffer.toString();
        		wechatservice.sendWeChatMsgCommonMethod1(map.get("FromUserName"),content);
            	content=null;
        		
        	}else if("D".equals(map.get("Content")) 
        			||"d".equals(map.get("Content"))){
        		
                StringBuffer buffer = new StringBuffer();
        		buffer.append("D、财运状况不好").append("\n");
        		buffer.append("😔2018年你的财运状况不好。在这一年里，你的正财运和偏财运都很低迷，正财方面财富有所减少，累积的速度开始变慢，甚至停滞。另外今年，你的部分开销将变得格外的大，尤其是家庭方面的开销。有可能给你造成很大的压力，甚至导致一些疾病。").append("\n");
        		
        		content=buffer.toString();
        		wechatservice.sendWeChatMsgCommonMethod1(map.get("FromUserName"),content);
            	content=null;
        		
        	}else{
        		wechatservice.sendWeChatImgCommonMethod1(map.get("FromUserName"),WeixinUtil.ID4);
        	}
        }
	}
	
	/**
	 * 微信分享（jsapi）
	 *@param shareUrl
	 */
	@ResponseBody
	@RequestMapping("/getShareParameter")
	public Object getShareParameter(HttpServletRequest request, HttpServletResponse response,String shareUrl,String type) throws Exception {
		if(type!=null){
			String bodyParams = "grant_type=client_credential&appid=wx09d9aee6ef3049bc&secret=9f3939d2053fe9f97a1ac2e3dc701602";
			String access_token = wechatservice.getAccessToken();
			String  ticket = WeixinUtil.getJsApiTicket(access_token);
			
			Map map = new HashMap();

		    String nonceStr = Sha1.getNonceStr(); 
		    String timeStamp=Sha1.getTimeStamp();//时间戳  
		    String signValue = "jsapi_ticket="+ticket+"&noncestr="+nonceStr+"&timestamp="+timeStamp+"&url="+shareUrl;  
		    String signature = Sha1.getSha1(signValue);
			map.put("timeStamp", timeStamp);
			map.put("nonceStr", nonceStr);
			map.put("signature", signature);
			return PackageUtil.packageParams(200,"success",map,"");
		}
		Map map = new HashMap();
		String ticket = wechatLoginService.getJsApiTicket();

	    String nonceStr = Sha1.getNonceStr(); 
	    String timeStamp=Sha1.getTimeStamp();//时间戳  
	    String signValue = "jsapi_ticket="+ticket+"&noncestr="+nonceStr+"&timestamp="+timeStamp+"&url="+shareUrl;  
	    String signature = Sha1.getSha1(signValue);
		map.put("timeStamp", timeStamp);
		map.put("nonceStr", nonceStr);
		map.put("signature", signature);

		return PackageUtil.packageParams(200,"success",map,"");
	}
	
	/**
	 * 公众号获取accessToken 
	 */
	@ResponseBody
	@RequestMapping("/accessToken")
	public Object accessToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		String access_token = wechatservice.getAccessToken();

		return PackageUtil.packageParams(200,"success",access_token,"");
	}
	/**
	 * 获取QrCode url
	 */
	@RequestMapping("/getQrCode")
	public void getQrCode(HttpServletRequest request, HttpServletResponse response,String url) throws Exception {
		ServletOutputStream stream = null;
        try {
            int width = 800;//图片的宽度
            int height = 800;//高度
            stream = response.getOutputStream();
            QRCodeWriter writer = new QRCodeWriter();
            BitMatrix m = writer.encode(url, BarcodeFormat.QR_CODE, height, width);
            MatrixToImageWriter.writeToStream(m, "png", stream);
            
        } catch (WriterException e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
	}
	
	
	/**
	 * 获取openId
	 */
	@RequestMapping("/getOpenId")
	public void getOpenId(HttpServletRequest request, HttpServletResponse response,String url) throws Exception {
		String code = request.getParameter("code");
		if (!"authdeny".equals(code)) {
    	   WeixinOauth2TokenVO weixinOauth2Token = wechatLoginService.getOpenId(ConfigUtil.WECHAT_PUBLIC_APPID,ConfigUtil.WECHAT_PUBLIC_SECRET,code);
            // 网页授权接口访问凭证
            String accessToken = weixinOauth2Token.getAccessToken();
            System.out.println(JSON.toJSONString(weixinOauth2Token));
            // 用户标识
            String unionId="";
            if(weixinOauth2Token.getUnionId()!=null&&"".equals(weixinOauth2Token.getUnionId())){
            	unionId=weixinOauth2Token.getUnionId();
            }
            String openIdAndUnionId = weixinOauth2Token.getOpenId()+","+unionId;
            response.getWriter().print(openIdAndUnionId);
            response.getWriter().close();
        }
	}
	
	
	/**
	 * 获取openId
	 */
	@ResponseBody
	@RequestMapping("/wechatInfo")
	public Object wechatInfo(HttpServletRequest request, HttpServletResponse response,String url) throws Exception {
		String openId=request.getParameter("openId");
		
		String access_token=wechatservice.getAccessToken();
		JSONObject obj2=WeixinUtil.getInfo(openId, access_token);
		return PackageUtil.packageParams(200,"success",obj2,"");
	}
	/**
	 * 获取AccessToken
	 */
	@ResponseBody
	@RequestMapping("/AccessToken")
	public Object AccessToken(HttpServletRequest request, HttpServletResponse response,String url) throws Exception {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		java.util.Date date=new java.util.Date();  
		String now=sdf.format(date); 
		String access_token =  WeixinUtil.getAccessToken();
		JSONObject updObj = new JSONObject();
		updObj.put("token", access_token);
		
			updObj.put("time", now);
		
		configService.updConfValueByKey("ACCESS_TOKEN",updObj.toJSONString());
		return PackageUtil.packageParams(200,"success",updObj,"");
	}
}
